<template>
  <BasicDrawer
    :destroy-on-close="true"
    :showFooter="true"
    width="40%"
    title="授权菜单"
    @ok="handleOk"
    @register="registerDrawer"
  >
    <Button @click="handleExpanded" type="primary">{{ isExpanded ? '折叠' : '展开' }}</Button>
    <Tree
      :fieldNames="{ title: 'name', key: 'id' }"
      v-model:expandedKeys="expandedKeys"
      v-model:checkedKeys="checkedKeys"
      @check="handleCheck"
      checkable
      :tree-data="treeData"
    />
  </BasicDrawer>
</template>
<script setup lang="ts">
  import { BasicDrawer, useDrawer } from '@/components/Drawer';
  import { ref } from 'vue';
  import { Tree, Button } from 'ant-design-vue';
  import { sysMenuPage } from '@/api/sys/menu';
  import { saveRoleMenu, roleMenuIds } from '@/api/sys/rbac';
  import { getAllLeafIds, getAllNodeIds } from '@/utils/tree';

  const expandedKeys = ref<string[]>([]);
  const checkedKeys = ref([]);
  const treeData = ref([]);
  const currentRecord = ref();
  const tableRef = ref();
  const leafIds = ref<string[]>([]);
  const allLeafIds = ref<string[]>([]);
  const sumbitCheckedKeys = ref<string[]>([]);
  const isExpanded = ref(false);
  const [registerDrawer, { openDrawer, setDrawerProps }] = useDrawer();
  const handleOk = () => {
    const roleMenus = sumbitCheckedKeys.value.map((menuId) => {
      return {
        roleId: currentRecord.value.id,
        menuId: menuId,
      };
    });
    setDrawerProps({
      confirmLoading: true,
    });
    saveRoleMenu(roleMenus).finally(() => {
      setDrawerProps({
        confirmLoading: false,
      });
    });
  };
  const handleCheck = (mCheckedKeys, e) => {
    // 提交的值==勾选的值+半选的值
    sumbitCheckedKeys.value = [...mCheckedKeys, ...e.halfCheckedKeys];
  };
  // 展开折叠处理
  const handleExpanded = () => {
    isExpanded.value = !isExpanded.value;
    if (isExpanded.value) {
      expandedKeys.value = allLeafIds.value;
    } else {
      expandedKeys.value = [];
    }
  };
  defineExpose({
    show(record, tableAction) {
      currentRecord.value = record;
      tableRef.value = tableAction;
      sysMenuPage({}).then((data) => {
        treeData.value = data;
        leafIds.value = getAllLeafIds(data);
        allLeafIds.value = getAllNodeIds(data);
      });
      roleMenuIds({
        roleId: currentRecord.value.id,
      }).then((data) => {
        // 选中值，一定为叶子节点
        checkedKeys.value = data.filter((menuId) => {
          return leafIds.value.includes(menuId);
        });
        sumbitCheckedKeys.value = data;
      });
      openDrawer();
    },
  });
</script>
